
  struct ListNode {
      int val;
      ListNode *next;
      ListNode() : val(0), next(nullptr) {}
      ListNode(int x) : val(x), next(nullptr) {}
     ListNode(int x, ListNode *next) : val(x), next(next) {}
  };
 
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {

        int m = 0;
        ListNode* cur = head;
        while (cur) {
            m++;
            cur = cur->next;
        }
        cur = head;
        ListNode* front = cur;
        int r = m - n;
        while (r--) {
            front = cur;
            cur = cur->next;
        }
        front->next = cur->next;
        bool ret = front == cur;
        ListNode* next = cur->next;
        return ret ? cur->next : head;
    }
};